from decimal import *
setcontext(ExtendedContext)

from copy import *

import locale
locale.setlocale(locale.LC_ALL, '')

class currency(Decimal):
   '''
   >>> c = currency(43)
   >>> str(c), c + 2
   ('R43.00', currency("R45.00"))
   >>> print c
   R43.00
   >>> c = currency('R12.3')
   >>> str(c), c * 2
   ('R12.30', currency("R24.60"))
   >>> c = currency('bugger all')
   >>> str(c), c
   ('R0.00', currency("R0.00"))
   '''

   def __new__(cls, value=0):
      value = str(value)
      symbols = locale.localeconv()
      value = str(value)
      value = value.replace(symbols['currency_symbol'], '')
      value = value.replace(symbols['mon_thousands_sep'], '')
      value = value.replace(symbols['mon_decimal_point'], '.')
      value = Decimal(value)
      if value._isnan():
         value = Decimal('0.0')
      #value = value.quantize(Decimal('0.01'))
      return Decimal.__new__(cls, value)

   __add__ = lambda self, other: currency(Decimal.__add__(self, other))
   __div__ = lambda self, other: currency(Decimal.__div__(self, other))
   __mul__ = lambda self, other: currency(Decimal.__mul__(self, other))
   __sub__ = lambda self, other: currency(Decimal.__sub__(self, other))
      
   def __str__(self):
      return locale.currency(float(Decimal(self)))

   def __repr__(self):
      return 'currency("%s")' % str(self)
      
import doctest
doctest.testmod()

